package com.yutianran.ezadapter.rv;

import android.support.v7.widget.RecyclerView;

import com.yutianran.ezadapter.LayoutHolder;
import com.yutianran.ezadapter.LayoutPlayer;
import com.yutianran.ezadapter.TypeHelper;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

public class RvHelper {

    private RvAdapter adapter;
    private Map<Integer, LayoutPlayer<?>> playerMap;//layoutId --> player
    private Map<Class, Integer> layoutIdMap;//Class --> layoutId
    private List<Integer> layoutIds;// viewType --> layoutId

    /**
     * 以后再设置数据源，一般用于动态数据
     */
    public RvHelper() {
        playerMap = new HashMap<>();
        layoutIdMap = new HashMap<>();
        layoutIds = new ArrayList<>();
        adapter = new RvAdapter(this);
    }

    /**
     * 先设置数据源，一般用于静态数据
     *
     * @param data
     */
    public RvHelper(List<?> data) {
        playerMap = new HashMap<>();
        layoutIdMap = new HashMap<>();
        layoutIds = new ArrayList<>();
        adapter = new RvAdapter(this, data);
    }

    public static RvHelper create() {
        return new RvHelper();
    }

    public static RvHelper with(List<?> data) {
        return new RvHelper(data);
    }

    public <T> RvHelper register(LayoutHolder<T> holder) {
        return register(holder.getLayoutId(), holder);
    }

    public <T> RvHelper register(int layoutId, LayoutPlayer<T> player) {
        playerMap.put(layoutId, player);
        layoutIds.add(layoutId);
        layoutIdMap.put(TypeHelper.getActualTypeArguments(player), layoutId);
        return this;
    }

    public RvHelper into(RecyclerView recyclerView) {
        adapter.initLayoutIdMap();
        recyclerView.setAdapter(adapter);
        return this;
    }

    public void setData(List<?> data) {
        adapter.setData(data);
    }

    public RvAdapter getAdapter() {
        return adapter;
    }

    public Map<Integer, LayoutPlayer<?>> getPlayerMap() {
        return playerMap;
    }

    public Map<Class, Integer> getLayoutIdMap() {
        return layoutIdMap;
    }

    public List<Integer> getLayoutIds() {
        return layoutIds;
    }

}
